"""
Grave! Important! Важно!

Proletoj el ĉiuj landoj, unuiĝu!
Workers of the world, unite!
Пролетарии всех стран, соединяйтесь!

https://tkom.pro
"""

from django.contrib import admin
from django import forms
from django.utils.translation import gettext_lazy as _
import json

from .models import *
from siriuso.forms.widgets import LingvoInputWidget, LingvoTextWidget
from universo_bazo.models import Realeco
from siriuso.utils.admin_mixins import TekstoMixin


# Форма категорий ресурсов
class ResursoKategorioFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)

    class Meta:
        model = ResursoKategorio
        fields = [field.name for field in ResursoKategorio._meta.fields if field.name not in ('krea_dato', 'uuid')]\
                 + ['realeco',]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Категорий ресурсов
@admin.register(ResursoKategorio)
class ResursoKategorioAdmin(admin.ModelAdmin, TekstoMixin):
    form = ResursoKategorioFormo
    list_display = ('id','nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    filter_horizontal = ('realeco',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = ResursoKategorio


# Форма типов связей категорий ресурсов между собой
class ResursoKategorioLigiloTipoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)

    class Meta:
        model = ResursoKategorioLigiloTipo
        fields = [field.name for field in ResursoKategorioLigiloTipo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Типы связей категорий ресурсов между собой
@admin.register(ResursoKategorioLigiloTipo)
class ResursoKategorioLigiloTipoAdmin(admin.ModelAdmin, TekstoMixin):
    form = ResursoKategorioLigiloTipoFormo
    list_display = ('id','nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = ResursoKategorioLigiloTipo


# Форма связей категорий ресурсов между собой
class ResursoKategorioLigiloFormo(forms.ModelForm):
    
    class Meta:
        model = ResursoKategorioLigilo
        fields = [field.name for field in ResursoKategorioLigilo._meta.fields if field.name not in ('krea_dato', 'uuid')]


# Связи категорий ресурсов между собой
@admin.register(ResursoKategorioLigilo)
class ResursoKategorioLigiloAdmin(admin.ModelAdmin, TekstoMixin):
    form = ResursoKategorioLigiloFormo
    list_display = ('uuid','posedanto','tipo','ligilo')
    exclude = ('uuid',)
    class Meta:
        model = ResursoKategorioLigilo


# Форма типов ресурсов
class ResursoTipoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)
    realeco = forms.ModelMultipleChoiceField(
        label=_('Параллельные миры'),
        queryset=Realeco.objects.filter(forigo=False, publikigo=True)
    )

    class Meta:
        model = ResursoTipo
        fields = [field.name for field in ResursoTipo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Типы ресурсов
@admin.register(ResursoTipo)
class ResursoTipoAdmin(admin.ModelAdmin, TekstoMixin):
    form = ResursoTipoFormo
    list_display = ('id','nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = ResursoTipo


# Форма классов ресурсов
class ResursoKlasoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)
    realeco = forms.ModelMultipleChoiceField(
        label=_('Параллельные миры'),
        queryset=Realeco.objects.filter(forigo=False, publikigo=True)
    )

    class Meta:
        model = ResursoKlaso
        fields = [field.name for field in ResursoKlaso._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Типы ресурсов
@admin.register(ResursoKlaso)
class ResursoKlasoAdmin(admin.ModelAdmin, TekstoMixin):
    form = ResursoKlasoFormo
    list_display = ('nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = ResursoKlaso


# Форма модификации ресурсов
class ResursoModifoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)

    class Meta:
        model = ResursoModifo
        fields = [field.name for field in ResursoModifo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Модификации ресурсов
@admin.register(ResursoModifo)
class ResursoModifoAdmin(admin.ModelAdmin, TekstoMixin):
    form = ResursoModifoFormo
    list_display = ('id','nomo_teksto','integreco','potenco','volumeno_interna','volumeno_ekstera','posedanto')
    exclude = ('uuid',)
    class Meta:
        model = ResursoModifo


# Форма типов характеристик модификаций ресурсов
class ResursoModifoKarakterizadoTipoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)

    class Meta:
        model = ResursoModifoKarakterizadoTipo
        fields = [field.name for field in ResursoModifoKarakterizadoTipo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Характеристики модификаций ресурсов
@admin.register(ResursoModifoKarakterizadoTipo)
class ResursoModifoKarakterizadoTipoAdmin(admin.ModelAdmin, TekstoMixin):
    form = ResursoModifoKarakterizadoTipoFormo
    list_display = ('id', 'nomo_teksto')
    exclude = ('uuid',)
    class Meta:
        model = ResursoModifoKarakterizadoTipo


# Форма характеристик модификаций ресурсов
class ResursoModifoKarakterizadoFormo(forms.ModelForm):
    
    class Meta:
        model = ResursoModifoKarakterizado
        fields = [field.name for field in ResursoModifoKarakterizado._meta.fields if field.name not in ('krea_dato', 'uuid')]


# Характеристики модификаций ресурсов
@admin.register(ResursoModifoKarakterizado)
class ResursoModifoKarakterizadoAdmin(admin.ModelAdmin, TekstoMixin):
    form = ResursoModifoKarakterizadoFormo
    list_display = ('uuid', 'tipo', 'latero_karakterizado')
    exclude = ('uuid',)
    list_filter = ('latero_karakterizado',)
    class Meta:
        model = ResursoModifoKarakterizado


# Форма связей модификаций с характеристиками модификаций
class ResursoModifoKarakterizadoLigiloFormo(forms.ModelForm):
    
    class Meta:
        model = ResursoModifoKarakterizadoLigilo
        fields = [field.name for field in ResursoModifoKarakterizadoLigilo._meta.fields if field.name not in ('krea_dato', 'uuid')]


# Связи модификаций с характеристиками модификаций
@admin.register(ResursoModifoKarakterizadoLigilo)
class ResursoModifoKarakterizadoLigiloAdmin(admin.ModelAdmin, TekstoMixin):
    form = ResursoModifoKarakterizadoLigiloFormo
    list_display = ('uuid','modifo','karakterizado')
    exclude = ('uuid',)
    class Meta:
        model = ResursoModifoKarakterizadoLigilo


# Форма состояния модификаций ресурсов
class ResursoModifoStatoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)

    class Meta:
        model = ResursoModifoStato
        fields = [field.name for field in ResursoModifoStato._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Состояния модификаций ресурсов
@admin.register(ResursoModifoStato)
class ResursoModifoStatoAdmin(admin.ModelAdmin, TekstoMixin):
    form = ResursoModifoStatoFormo
    list_display = ('id','nomo_teksto','integreco','potenco','posedanto','stato_antaua','stato_sekva')
    exclude = ('uuid',)
    class Meta:
        model = ResursoModifoStato


# Форма типов мест хранения ресурсов
class ResursoStokejoTipoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)

    class Meta:
        model = ResursoStokejoTipo
        fields = [field.name for field in ResursoStokejoTipo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Типы мест хранения ресурсов
@admin.register(ResursoStokejoTipo)
class ResursoStokejoTipoAdmin(admin.ModelAdmin, TekstoMixin):
    form = ResursoStokejoTipoFormo
    list_display = ('id','nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = ResursoStokejoTipo


# Форма логических мест хранения ресурсов
class ResursoStokejoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Titolo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)

    class Meta:
        model = ResursoStokejo
        fields = [field.name for field in ResursoStokejo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Логические места хранения ресурсов
@admin.register(ResursoStokejo)
class ResursoStokejoAdmin(admin.ModelAdmin, TekstoMixin):
    form = ResursoStokejoFormo
    list_display = ('nomo_teksto','priskribo_teksto','posedanto','id','tipo')
    exclude = ('uuid',)
    class Meta:
        model = ResursoStokejo


# Места хранения в объектах модели объекта
# class ResursoStokejoInline(admin.TabularInline):
#     model = ResursoStokejo
#     fk_name = 'posedanto_modifo'
#     # form = ResursoStokejoFormo
#     extra = 1


# Владелец ресурса из таблицы связей
class ResursoLigiloInline(admin.TabularInline):
    model = ResursoLigilo
    fk_name = 'posedanto'
    extra = 1


# Форма ресурсов
class ResursoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)
    kategorio = forms.ModelMultipleChoiceField(
        label=_('Категория ресурсов'),
        queryset=ResursoKategorio.objects.filter(forigo=False, publikigo=True)
    )
    realeco = forms.ModelMultipleChoiceField(
        label=_('Параллельные миры'),
        queryset=Realeco.objects.filter(forigo=False, publikigo=True)
    )

    class Meta:
        model = Resurso
        fields = [field.name for field in Resurso._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Ресурсы
@admin.register(Resurso)
class ResursoAdmin(admin.ModelAdmin, TekstoMixin):
    form = ResursoFormo
    list_display = ('id','nomo_teksto','autoro_nn','priskribo_teksto')
    exclude = ('uuid',)
    inlines = ( ResursoLigiloInline,)
    autocomplete_fields = ['autoro']

    class Meta:
        model = Resurso


# Форма типов мест хранения ресурсов
class ResursoLigiloTipoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)

    class Meta:
        model = ResursoLigiloTipo
        fields = [field.name for field in ResursoLigiloTipo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Типы мест хранения ресурсов
@admin.register(ResursoLigiloTipo)
class ResursoLigiloTipoAdmin(admin.ModelAdmin, TekstoMixin):
    form = ResursoLigiloTipoFormo
    list_display = ('id','nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = ResursoLigiloTipo


# Форма типов цен ресурсов
class ResursoPrezoTipoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Titolo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)

    class Meta:
        model = ResursoPrezoTipo
        fields = [field.name for field in ResursoPrezoTipo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Типы цен ресурсов
@admin.register(ResursoPrezoTipo)
class ResursoPrezoTipoAdmin(admin.ModelAdmin, TekstoMixin):
    form = ResursoPrezoTipoFormo
    list_display = ('id','nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = ResursoPrezoTipo


# Форма видов цен ресурсов
class ResursoPrezoSpecoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Titolo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)

    class Meta:
        model = ResursoPrezoSpeco
        fields = [field.name for field in ResursoPrezoSpeco._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Виды цен ресурсов
@admin.register(ResursoPrezoSpeco)
class ResursoPrezoSpecoAdmin(admin.ModelAdmin, TekstoMixin):
    form = ResursoPrezoSpecoFormo
    list_display = ('id','nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = ResursoPrezoSpeco


# Форма статусов цен ресурсов
class ResursoPrezoStatusoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Titolo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)

    class Meta:
        model = ResursoPrezoStatuso
        fields = [field.name for field in ResursoPrezoStatuso._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Статус цен ресурсов
@admin.register(ResursoPrezoStatuso)
class ResursoPrezoStatusoAdmin(admin.ModelAdmin, TekstoMixin):
    form = ResursoPrezoStatusoFormo
    list_display = ('id','nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = ResursoPrezoStatuso


# Форма цен ресурсов
class ResursoPrezoFormo(forms.ModelForm):
    
    class Meta:
        model = ResursoPrezo
        fields = [field.name for field in ResursoPrezo._meta.fields if field.name not in ('krea_dato', 'uuid')]


# Цены ресурсов
@admin.register(ResursoPrezo)
class ResursoPrezoAdmin(admin.ModelAdmin, TekstoMixin):
    form = ResursoPrezoFormo
    list_display = ('uuid','resurso','posedanto_uzanto','posedanto_organizo','prezo')
    exclude = ('uuid',)
    class Meta:
        model = ResursoPrezo


# Форма мест хранения ресурсов
class ResursoLigiloFormo(forms.ModelForm):
    
    priskribo = forms.CharField(widget=LingvoTextWidget(), label=_('Priskribo'), required=False)

    class Meta:
        model = ResursoLigilo
        fields = [field.name for field in ResursoLigilo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Типы мест хранения ресурсов
@admin.register(ResursoLigilo)
class ResursoLigiloAdmin(admin.ModelAdmin, TekstoMixin):
    form = ResursoLigiloFormo
    list_display = ('uuid','posedanto','posedanto_stokejo','konektilo_posedanto','ligilo','konektilo_ligilo','tipo','priskribo_teksto')
    exclude = ('uuid',)
    class Meta:
        model = ResursoLigilo


